//
//  OMTPreviewViewController.m
//  OMTImagePicker
//
//  Created by yizhaorong on 2017/11/20.
//

#import "OMTPreviewViewController.h"
#import "YYAnimatedImageView.h"
#import "UIImageView+OMTAsset.h"
#import "MBProgressHUD.h"

#import "OMTImagePickerController.h"
#import "NSString+OMTImagePicker.h"

@interface OMTPreviewViewController ()

@property (nonatomic, strong) YYAnimatedImageView *previewView;

@property (nonatomic, strong) UIButton *selectButton;
// 图片对象
@property (nonatomic, strong) OMTAsset *asset;
// 图片选择器
@property (nonatomic, weak) OMTAlbumManager *albumManager;
@end

@implementation OMTPreviewViewController

#pragma mark - Lifecycle
- (void)dealloc {
    //[self unregisterNotifications];
}


- (instancetype)initWithAlbumManager:(OMTAlbumManager *)albumManager {
    if (self = [super init]) {
        self.albumManager = albumManager;
        [self setupSubviews];
        [self setLayout];
    }
    return self;
}

#pragma mark  -  View Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // [self registerNotifications];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)setupSubviews {
    // 初始化子视图
    NSString *(^Album18N)(NSString *) = [self.albumManager.builder.localizedString copy];
    self.view.backgroundColor = [UIColor whiteColor];
    _previewView = [YYAnimatedImageView new];
    _previewView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:_previewView];
    
    _selectButton = [UIButton new];
    [_selectButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_selectButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    [_selectButton setTitle:Album18N(@"omt_album_select") forState:UIControlStateNormal];
    [_selectButton setTitle:Album18N(@"omt_album_cancel") forState:UIControlStateSelected];
    [_selectButton addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    [_selectButton sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_selectButton];
}

- (void)setLayout {
    // 设置或更新布局
    CGFloat padding = 10;
    CGFloat previewY = padding;
    CGFloat previewW = CGRectGetWidth(self.view.frame) - 2 * padding;
    CGFloat previewH = CGRectGetHeight(self.view.frame) - previewY - padding;
    CGFloat previewX = (CGRectGetWidth(self.view.frame) - previewW) / 2;
    CGRect previewFrame = CGRectMake(previewX, previewY, previewW, previewH);
    self.previewView.frame = previewFrame;
    
    [self.selectButton sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.selectButton];
}

#pragma mark - Notifications

#pragma mark - SetupData

#pragma mark - Actions
- (void)selectAction:(UIButton *)sender {
    OMTImagePickerBuilder *builder = self.albumManager.builder;
    NSString *(^Album18N)(NSString *) = [builder.localizedString copy];
    OMTAlbumManager *albumManager = self.albumManager;
    if (albumManager.builder.showVedio) {
        for (OMTAsset *asset in albumManager.selectedPhotos) {
            asset.selected = NO;
        }
        [albumManager.selectedPhotos removeAllObjects];
    }
    
    if (albumManager.builder.showVedio
        && albumManager.builder.showVedio) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.detailsLabel.text = [Album18N(@"omt_album_exceeds_maximun_limit") picker_replacePatternBy:[NSString stringWithFormat:@"%ld",albumManager.builder.maxSelectCount], nil];
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        return;
    }
    
    self.selectButton.selected = !sender.isSelected;
    self.asset.selected = self.selectButton.isSelected;
    if (self.asset.selected) {
        [albumManager.selectedPhotos addObject:self.asset];
    } else {
        [albumManager.selectedPhotos removeObject:self.asset];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:OMTAssetAssetSelectedStateChangedNotification object:self.asset];
    [self setLayout];
}

#pragma mark - Private
- (void)fetchOriginImageWithAsset:(OMTAsset *)asset {
    OMTAlbumManager *albumManager = self.albumManager;
    __weak typeof(self) weakSelf = self;
    [albumManager originalPhotoWithAsset:asset completion:^(UIImage *image, NSData *imageData, NSDictionary *info, OMTAsset *asset, BOOL finished) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (!finished) return;
        strongSelf.previewView.image = image;
        [strongSelf setLayout];
    }];
}

#pragma mark - Public


#pragma mark - Protocol conformance


#pragma mark - Lazyload

#pragma mark - Custom Accessors
//自定义 setter getter
- (void)setAsset:(OMTAsset *)asset placeholder:(UIImage *)placeholder {
    self.asset = asset;
    __weak typeof(self) weakSelf = self;
    self.previewView.image = placeholder;
    OMTAlbumManager *albumManager = self.albumManager;
    [albumManager photoWithAsset:asset targetWitdh:albumManager.builder.photoWidth completion:^(UIImage *photo, NSData *imageData, NSDictionary *info, BOOL isDegraded, OMTAsset *asset, BOOL finished) {
        typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (!finished) return;
        strongSelf.selectButton.selected = asset.isSelected;
        strongSelf.previewView.image = photo;
        [strongSelf setLayout];
        
        if (asset.isGIF) {
            [strongSelf fetchOriginImageWithAsset:asset];
        }
    }];
}

@end
